package com.sina.shop.manage.service.log;

import com.sina.shop.core.exception.client.DataException;
import com.sina.shop.core.exception.server.CreateException;
import com.sina.shop.core.exception.server.ResourceExistsException;
import com.sina.shop.core.exception.server.UpdateException;
import com.sina.shop.domain.admin.Admin;
import com.sina.shop.domain.log.Log;
import com.sina.shop.manage.dao.admin.AdminManageDao;
import com.sina.shop.manage.dao.log.LogManageDao;
import com.sina.shop.service.ShopDataSourceService;
import com.sina.shop.util.ResultCode;
import com.sina.shop.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

import static com.sina.shop.service.ServiceConstant.SHOP_TX;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2018-01-12-10:11
 */
@Service("logManageService")
public class LogManageServiceImpl extends ShopDataSourceService implements LogManageService {

    @Autowired
    @Qualifier("logManageDao")
    private LogManageDao logManageDao;

    @Autowired
    @Qualifier("adminManageDao")
    private AdminManageDao adminManageDao;

    @Override
    @Transactional(value = SHOP_TX, readOnly = true, isolation = Isolation.READ_COMMITTED)
    public List<Map<String, Object>> getLogList(Log log, Long[] count) {


        Admin admin = null;
        if (log.getAdmin() != null && !StringUtils.isEmpty(log.getAdmin().getAccount())) {

            admin = adminManageDao.getAdmin(log.getAdmin().getAccount());
            if (admin == null) {
                admin = new Admin();
            }
        }

        log.setAdmin(admin);

        if (count != null && count.length > 0) {
            count[0] = logManageDao.getLogCount(log);
        }

        return logManageDao.getLogList(log);
    }

    @Override
    @Transactional(value = SHOP_TX, isolation = Isolation.READ_COMMITTED)
    public Log saveLog(Log log) throws CreateException, ResourceExistsException, DataException {
        try {

            logManageDao.save(log);
            logManageDao.flush();
            return log;
        } catch (DataAccessException e) {
            LOG.error(" {} save Log error.", Log.class, e);
            throw new UpdateException(ResultCode.dataAccessError, e.getMessage(), e);
        }
    }
}
